﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using LastoRevival.Service.Contracts.Models;

namespace LastoRevival.Service.Implementations.Data.Sql.Converters
{
	public class ViewPostModelCreator
	{

		private ThreadCreator threadConverter;

		public ViewPostModelCreator(ThreadCreator threadConverter)
		{
			this.threadConverter = threadConverter;
		}

		public ViewPostModel Create(DataRow activePost, DataRowCollection messageRows)
		{
			var post = new ViewPostModel
			{
				Body = string.Format("{0}", activePost["body"]),
				DatePosted = (DateTime)activePost["dateposted"],
				ForumID = (int)activePost["forumid"],
				PostID = (int)activePost["id"],
				ParentPostID = (int?)activePost["thread_parent"],
				// stick?
				Subject = string.Format("{0}", activePost["subject"]),
				ThreadID = (int)activePost["thread_id"],
				Views = (int)activePost["threadviews"],
				LastEdit = activePost["lastedit"] as DateTime?,
				LastEditedBy = string.Format("{0}", activePost["lasteditedby"]),
				AuthorPostCount = (int)activePost["postcount"],
				Client = string.Format("{0}", activePost["client"]),
				IP = string.Format("{0}", activePost["ip"]),
				Locked = (bool)activePost["locked"],
				Signature = string.Format("{0}", activePost["signature"]),
				GroupName = string.Format("{0}", activePost["groupname"]),
			};

			// if no userID, use the static name on the post (for legacy  support)
			// and the anonymousID
			var userID = activePost["userID"] as int?;
			if (!userID.HasValue)
			{
				post.UserID = UserProfileDetails.AnonymousUserID;
				post.UserName = string.Format("{0}", activePost["staticUsername"]);
			}
			else
			{
				post.UserID = userID.Value;
				post.UserName = string.Format("{0}", activePost["username"]);
			}
						
			// fix threadid
			if (post.ThreadID == 0) { post.ThreadID = post.PostID; }

			post.Thread = threadConverter.Convert(messageRows.OfType<DataRow>());

			return post;
		}

	}
}
